package com.atguigu.service.impl;

import com.atguigu.entity.Dish;
import com.atguigu.dto.DishDto;
import com.atguigu.entity.DishFlavor;
import com.atguigu.mapper.DishMapper;
import com.atguigu.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Resource
    private DishFlavorServiceImpl dishFlavorService;

    /**
     * 新增菜品，同时保存相应的口味数据
     * @param dishDto
     */
    @Transactional
    public void saveWithDishFalvor(DishDto dishDto) {
        //保存菜品的信息到菜品表
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();

        Long dishId = dishDto.getId();//菜品ID

        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }

        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据dishID将Dish转换为DishDto类型
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishDto queryDishDto(String id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        //将Dish对象复制到DishDto对象
        BeanUtils.copyProperties(dish,dishDto);
        //根据dishId获取该菜品对应的口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(StringUtils.isNotBlank(id),DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        //将口味放入DishDto对象
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    /**
     * 将修改好的菜品信息保存到数据库中
     * @param dishDto
     */
    @Transactional
    public void updateDishDto(DishDto dishDto){
        //更新DishDto中dish的基本信息
        this.updateById(dishDto);
        //根据dishId,删除dish_flavor表中的数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        //为dishFalvors中的每条记录添加dishId
        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor : dishFlavors) {
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setCreateUser(dishDto.getUpdateUser());
        }
        //根据dishId,添加dish_flavor表中的数据
        dishFlavorService.saveBatch(dishFlavors);
    }
}
